<?php
// +----------------------------------------------------------------------
// | Description: 产品
// +----------------------------------------------------------------------
// | Author:  Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\model;

use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class ContractConfirmation extends Common
{
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'crm_contract_confirmation';
    protected $createTime = '';
    protected $updateTime = '';
    protected $autoWriteTimestamp = true;

    /**
     * [getDataList 确认函list]
     * @author 
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */     
    public function getDataList($request)
    {
        $search = $request['search'];
        $where['title'] = ['like', '%'.$search.'%'];
        $list=$this->where($where)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->select();
        $dataCount=$this->where($where)->count();
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }
    public function getList()
    {
        $list = $this->field("confirmation_id type_id,title name,remark")->order('confirmation_id desc')->select();
        return $list ? : [];
    }
    /**
     * 合同产品确认函详情
     * @param  $id 确认函ID
     * @return
     */
    public function getDataById($contract_id,$product_id)
    {
        $map['product_id'] = $product_id;
        $map['contract_id'] = $contract_id;
        $dataInfo = $this->where($map)->select();
        if (!$dataInfo) {
            $this->error = '数据不存在或已删除';
            return false;
        }
        $data=[];
        foreach ($dataInfo as &$v){
            if($v["name"]=="服务期数"){
                continue;
            }
            if($v["name"]=="记账单量"){
                continue;
            }
            if($v["name"]=="记账类型"){
                continue;
            }
            if($v["name"]=="原销售"){
                continue;
            }
            $v["config"]=json_decode($v["config"],true);
            $v["value_data"] = $v["value_data"] ? json_decode($v["value_data"],true) : '--';
            if(!$v["value_data"]) {
                $v["value_data"] = '';
            }
            $data[]=$v;

        }
        return $data;
    }

    /**
     * 编辑合同产品确认函
     * @author
     * @param
     * @return
     */
    public function updateDataById($param)
    {
        if ($param['confirmation']) {
            //产品数据处理
            $data["confirmation"][]=$param["confirmation"];
            $resConfirmation = $this->createObject($data);
            if ($resConfirmation == false) {
                $this->error = '确认函数据修改失败';
                return false;
            }
            return true;
        }
        return true;
    }
    /**
     * 合同产品确认函创建
     * @return
     */
    public function createObject( $param,$contract_id)
    {
        /*if(empty($contract_id)){
            $this->error = '确认函数据创建失败';
            return false;
        }*/
        if ($param['confirmation']) {
            $confirmation = [];
            // 启动事务
            Db::startTrans();
            try {
                $update=false;
                foreach ($param['confirmation'] as $k => $val) {
                    foreach ($val as $key=>$value){
                        if(isset($value["contract_confirmation_id"]) && !empty($value["contract_confirmation_id"])){
                            /*服务公司可以后面修改填写；服务期数、记账单量、订单类型、原销售不允许修改*/
                            if($value["name"]=="服务公司"){
                                db("crm_contract")->where(["contract_id"=>$value["contract_id"]])->update(["name"=>$value["value_data"]]);
                            }
                            if($value["name"]=="服务期数"){
                                continue;
                            }
                            if($value["name"]=="记账单量"){
                                continue;
                            }
                            if($value["name"]=="记账类型"){
                                continue;
                            }
                            if($value["name"]=="原销售"){
                                continue;
                            }
                        }
                        $confirmation[$key]['confirmation_id'] = $value['confirmation_id'];//确认函id
                        $confirmation_name=Confirmation::where(["confirmation_id"=>$value['confirmation_id']])->value("title");
                        $confirmation[$key]['confirmation_name'] = empty($confirmation_name)?'':$confirmation_name;//确认函名称
                        $confirmation[$key]['name'] = $value['name'];
                        $confirmation[$key]['value_data'] = json_encode($value['value_data']);
                        $confirmation[$key]['type'] = $value['type'];
                        $confirmation[$key]['is_must'] = $value['is_must'];
                        $confirmation[$key]['confirmation_category_id'] = $value['confirmation_category_id'];//id
                        //修改已绑定合同的确认函
                        if(isset($value["contract_confirmation_id"]) && !empty($value["contract_confirmation_id"])){
                            $update=true;
                            $confirmation[$key]['contract_confirmation_id'] = $value['contract_confirmation_id'];//id
                            if(isset($contract_id)){
                                $confirmation[$key]['contract_id'] = $contract_id;//合同id
                            }else{
                                $confirmation[$key]['contract_id'] = $value["contract_id"];//合同id
                            }

                        }else{
                            $confirmation[$key]['contract_id'] = $contract_id;//合同id
                            $confirmation[$key]['product_id'] = $value["product_id"];//产品id
                            $config=ConfirmationCategory::where(["confirmation_category_id"=>$value['confirmation_category_id']])->value("config");
                            $confirmation[$key]["config"]=empty($config)?'':$config;
                        }
                    }
                }
                if(!empty($confirmation)){
                    //新增
                    if($update){
                        $this->saveALL($confirmation);
                    }else{
                        db("crm_contract_confirmation")->insertAll($confirmation);
                    }
                }
                // 提交事务
                Db::commit();
                return true;
            } catch (\Exception $e) {
                $this->error = '确认函数据创建失败';
                // 回滚事务
                Db::rollback();
                return false;
            }
        }
    }
}
